package library.commands;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import library.domain.User;
import library.service.UserService;

public class AuthCommand extends Command {

    public AuthCommand(ObjectInputStream input, ObjectOutputStream output, Socket socket) {
        super(input, output, socket);
    }

    @Override
    public void execute() throws Exception {
        User user = (User) input.readObject();
        if (user.getId() == -1) {
            CommandManager.getInstance().addSession(socket, user);
            output.writeObject(user);
        } else {

            // TODO: GET USER FROM DB!!!
            // Если пользователя нету - вернуть юзера с ИД = нулл
            // user.getLogin() и user.getPassword() - пароль в сыром виде
            //User newUser = new User();
            UserService userService = serviceLocator.getService(UserService.class);
            User newUser = userService.findUser(user.getLogin(), user.getPassword());

            if (newUser == null) {
                newUser = new User();
                newUser.setId(null);
            }

            output.writeObject(newUser);
            CommandManager.getInstance().addSession(socket, newUser);
        }
    }
}
